package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SQLUtil {

    private static final Logger logger = LoggerFactory.getLogger(SQLUtil.class);

    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o: (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    public static String setConditions(String sql, Map<String, Object> conditions) {
        for (Map.Entry<String, Object> entry : conditions.entrySet()) {
            String paramKey = entry.getKey();
            String paramValue = "";
            //处理select组件值，拼成逗号分隔的字符串，在SQL中使用IN来做条件。
            if (entry.getValue() instanceof ArrayList<?>) {
                List<String> valueList = castList(entry.getValue(), String.class);
                if (valueList.size() == 0) {
                    paramValue = " LIKE '%'";
                } else {
                    for (String val: valueList) {
                        paramValue += "," + "'" + val + "'";
                    }
                    paramValue = paramValue.substring(1, paramValue.length());
                    paramValue = " IN (" + paramValue + ")";
                }
            } else {
                paramValue = entry.getValue().toString();
            }
            sql = sql.replace("[" + paramKey + "]", paramValue);
        }
        logger.info(sql);
        return sql;
    }
}
